package com.nashuju.web.service.role;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.durcframework.core.expression.ExpressionQuery;
import org.durcframework.core.expression.subexpression.ValueExpression;
import org.durcframework.core.service.CrudService;
import org.springframework.stereotype.Service;

import com.nashuju.web.dao.role.RolePermissionDao;
import com.nashuju.web.entity.role.RolePermission;
import com.nashuju.web.entity.sys.FunctionRoleParam;
import com.nashuju.web.entity.sys.SysFunction;

@Service
public class RolePermissionService extends CrudService<RolePermission, RolePermissionDao> {

    /**
     * 根据功能查询角色权限
     * @param function
     * @return
     */
    public List<RolePermission> getRolePermissionByFunction(SysFunction function) {
        ExpressionQuery query = new ExpressionQuery();
        query.add(new ValueExpression("sf_id", function.getSfId()));
        query.setQueryAll(true);

        return this.find(query);
    }

    /**
     * 根据角色查询功能
     * @param roleId
     * @return
     */
    public List<RolePermission> getRolePermissionByRole(int roleId) {
        ExpressionQuery query = new ExpressionQuery();
        query.add(new ValueExpression("role_id", roleId));
        query.setQueryAll(true);

        return this.find(query);
    }

    /**
     * 批量设置系统功能权限
     * @param sfId
     * @param roleIds
     */
    public void setSysFunctionRole(int sfId, List<Integer> roleIds) {
        this.delBySfId(sfId); // 先删除之前的

        FunctionRoleParam param = new FunctionRoleParam();
        param.setRoleIds(roleIds);
        param.setSfId(sfId);

        this.getDao().setFunctionRole(param);
    }

    /**
     * 设置系统功能权限
     * @param roleId
     * @param sfId
     */
    public void setSysFunctionRole(List<Integer> sfIds, int roleId) {
        delByRoleId(roleId); // 删除该角色所有的操作权限

        // 添加新的操作权限
        if (CollectionUtils.isNotEmpty(sfIds)) {
            RolePermission rp = null;
            for (Integer sfId : sfIds) {
                rp = new RolePermission();
                rp.setRoleId(roleId);
                rp.setSfId(sfId);

                this.save(rp);
            }
        }
    }

    public void delBySfId(int sfId) {
        this.getDao().delBySfId(sfId);
    }

    public void delByRoleId(int roleId) {
        this.getDao().delByRoleId(roleId);
    }

}
